#!/bin/bash
# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

function log {
  (>&2 echo "$(date '+%Y-%m-%d %H:%M:%S')] $@")
}

set -e
export TZ="UTC"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)"
cd "${SCRIPT_DIR}"

GIT_ROOT="$(git rev-parse --show-toplevel)"
cd "${GIT_ROOT}/python"

BRANCH="feature/bitmex_unavailability"

TODAY="$(date '+%Y%m%d')"
YESTERDAY="$(date '+%Y%m%d' -d '1 day ago')"
FROM_DATE="$(date '+%Y%m%d' -d '10 day ago')"

log "Bitmex unavailability update ${YESTERDAY}"
log "Preparing..."
git checkout master --quiet
git pull origin master --quiet
git checkout -B "${BRANCH}" --quiet

log "Fetching log..."
~/workspace/coin_deploy/support_monitor/pull_log.sh

log "Extracting unavailable intervals..."
./pyrunner coin/strategy/tool/bitmex_503_extractor.py \
    interval ~/data/log/*.eu-west-1 \
    --begin_time="${FROM_DATE}" \
    --end_time="${TODAY}" \
    --nohuman_readable \
    --exclude_regex="eth" \
    --merge_with coin/strategy/data/bitmex_unavailability.txt > bitmex_unavailability.txt

cp bitmex_unavailability.txt ~/ops/
mv bitmex_unavailability.txt coin/strategy/data/bitmex_unavailability.txt

./pyrunner coin/strategy/tool/bitmex_503_extractor.py \
    interval ~/data/log/strategy-13.eu-west-1/log_*ethusd* \
    --begin_time="${FROM_DATE}" \
    --end_time="${TODAY}" \
    --nohuman_readable \
    --merge_with coin/strategy/data/bitmex_ethusd_unavailability.txt > bitmex_ethusd_unavailability.txt

cp bitmex_ethusd_unavailability.txt ~/ops/
mv bitmex_ethusd_unavailability.txt coin/strategy/data/bitmex_ethusd_unavailability.txt

if ! git diff-index --quiet HEAD; then
  log "Pushing to github..."
  git add -u
  git commit -m "Update bitmex unavailability ${YESTERDAY}" --quiet
  git push origin "${BRANCH}" --quiet

  log "Making Pull-Request..."
  PR_URL=$(hub pull-request --no-edit --reviewer=jhkim-prestolabs)
  echo "${PR_URL}"
else
  log "No change"
fi

git checkout master --quiet
git pull origin master --quiet
log "Done"
